import socket
import time

from Exception import IpError

q = ...


class ServerNodeManage:
    @staticmethod
    def connect(ip_port):

        tcp_soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        tcp_soc.sendto(b"Hello,I am Your Master", ip_port)
        return tcp_soc

    @staticmethod
    def o_get_accept(onee, soc: socket.socket, using_method,timeout=None):
        """
        Oneesama 等待 Sister 报告
        !该方法具有阻塞态 请使用线程或者进程进行创建!
        :return:
        """
        starttime = time.time()
        while True:
            nowtime = time.time()
            if nowtime - starttime > timeout:
                using_method(f"【Oneesama】 已经超时 不再等待从服务器加入")
                break
            if onee.startAccept:
                client_socket, client_addr_info = soc.accept()
                SocketList = []
                for i in onee.SocketList:
                    ip = i.get("ip")
                    if ip is None:
                        raise IpError("你这个IP有问题诶")
                    elif ip == client_addr_info[0]:
                        i["socket"] = client_socket
                        break
                    SocketList.append(i)
                using_method(f"【Oneesama】 有Sister服务器加入 并开始等待数据与任务")

                is_full = True
                for i in onee.SocketList:
                    co = i.get("socket")
                    if co is None:
                        print(i)
                        is_full = False
                        break
                if is_full:
                    using_method(f"【Oneesama】 所有集群服务器开启并全部响应! 开始处理数据")
                    onee.startAccept = False
